package com.rules.admin.handler;

import com.gillion.grule.client.core.DataType;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DataTypeHandler implements TypeHandler<DataType> {
   public void setParameter(PreparedStatement ps, int i, DataType parameter, JdbcType jdbcType) throws SQLException {
      switch(parameter) {
      case Integer:
         ps.setInt(i, 0);
         break;
      case String:
         ps.setInt(i, 1);
         break;
      case Double:
         ps.setInt(i, 2);
         break;
      case Date:
         ps.setInt(i, 3);
         break;
      case Boolean:
         ps.setInt(i, 4);
         break;
      case List:
         ps.setInt(i, 6);
         break;
      case Long:
         ps.setInt(i, 7);
         break;
      default:
         ps.setInt(i, 5);
      }

   }

   public DataType getResult(ResultSet rs, String columnName) throws SQLException {
      int type = rs.getInt(columnName);
      return this.switchType(type);
   }

   public DataType getResult(ResultSet rs, int columnIndex) throws SQLException {
      int type = rs.getInt(columnIndex);
      return this.switchType(type);
   }

   public DataType getResult(CallableStatement cs, int columnIndex) throws SQLException {
      int type = cs.getInt(columnIndex);
      return this.switchType(type);
   }

   private DataType switchType(int type) {
      switch(type) {
      case 0:
         return DataType.Integer;
      case 1:
         return DataType.String;
      case 2:
         return DataType.Double;
      case 3:
         return DataType.Date;
      case 4:
         return DataType.Boolean;
      case 5:
      default:
         return DataType.Object;
      case 6:
         return DataType.List;
      case 7:
         return DataType.Long;
      }
   }
}
